package logic

import (
	"context"
	"fmt"
	"time"
	"user-sys/models"
	"user-sys/pkg"

	"user-sys/user_rpc/internal/svc"
	"user-sys/user_rpc/user_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *user_rpc.LoginRequest) (*user_rpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	if in.Phone == "" {
		Image_key := fmt.Sprintf("account form InageCaptcha:%s", in.Account)
		image_code, _ := models.RDB.Get(models.Ctx, Image_key).Result()
		if in.ImageCode != image_code {
			return nil, fmt.Errorf("图形验证码错误")
		}
		var key = fmt.Sprintf("account_count form login:%s", in.Account)
		count, _ := models.RDB.Get(models.Ctx, key).Int()
		if count == 3 {
			return &user_rpc.LoginResponse{}, fmt.Errorf("密码错误过多，账号暂时锁定")
		}
		if err := models.DB.Where("user_account = ?", in.Account).Limit(1).Find(&user).Error; err != nil {
			return &user_rpc.LoginResponse{}, fmt.Errorf("服务器繁忙")
		}
		if user.ID == 0 {
			return &user_rpc.LoginResponse{}, fmt.Errorf("账号未注册，请先注册")
		}
		if user.UserPassword != pkg.MD5(in.Password) {
			models.RDB.Incr(models.Ctx, key)
			if count == 2 {
				models.RDB.Expire(models.Ctx, key, 12*time.Hour)
			}
			return &user_rpc.LoginResponse{}, fmt.Errorf("账号或密码错误")
		}
	} else {
		if err := models.DB.Where("user_phone = ?", in.Phone).Limit(1).Find(&user).Error; err != nil {
			return &user_rpc.LoginResponse{}, fmt.Errorf("服务器繁忙")
		}
		if user.ID == 0 {
			return &user_rpc.LoginResponse{}, fmt.Errorf("该手机号暂未绑定账户")
		}
		Sms_key := fmt.Sprintf("phone from SmsCaptcha:%s", in.Phone)
		Sms_code, _ := models.RDB.Get(models.Ctx, Sms_key).Result()
		if in.SmsCode != Sms_code {
			return nil, fmt.Errorf("短信验证码错误")
		}
	}
	return &user_rpc.LoginResponse{
		Id: int64(user.ID),
	}, nil
}
